<template>
    <div>
        <el-form label-width="110px" size="small">
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="产品代码:" v-if="isBatchStock">
                        <RiskEntryInput @set-entry-data="getEntryslist" :returnDatas="instruction.fundCode" />
                    </el-form-item>
                    <el-form-item label="组合编码:" v-if="isBatchStock">
                        <el-select v-model="instruction.fundAccountCode" size="mini" @change="handleFundAccountCodeChange">
                            <el-option
                                v-for="i in computedFundAccountCodeSelectData"
                                :key="i.fundAccountCode"
                                :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                :value="i.fundAccountCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证券代码:" v-if="isBatchFund">
                        <el-select
                            ref="searchSelect"
                            size="mini"
                            clearable
                            filterable
                            :filter-method="getstockCodeList"
                            :loading="selectLoading"
                            v-model="instruction.stockCode"
                            @change="handleStockCode"
                            @visible-change="handleStockVisibleChange"
                            @focus="selectFocus"
                            @clear="getstockCodeList('')"
                        >
                            <el-option
                                v-for="i in stockCodeSelectData"
                                :key="i.stockCode"
                                :label="i.stockCode + ' ' + i.stockName"
                                :value="i.stockCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务类型:">
                        <el-select v-model="instruction.businClass" size="mini">
                            <el-option value="C" label="网下申购"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="委托方向:">
                        <el-select v-model="instruction.orderDirection" size="mini" :class="['font-color-' + textColor]">
                            <el-option value="C" label="申购" :style="handleTextColor('C')"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="交易对手:">
                        <el-select
                            v-model="instruction.opponentCode"
                            @change="getOpponentCode"
                            filterable
                            clearable
                            :filter-method="getOpponentCode"
                            :loading="selectLoading"
                            size="mini"
                            @visible-change="handleOpponentVisibleChange"
                        >
                            <el-option
                                v-for="i in opponentCodeSelectData"
                                :key="i.dictKey"
                                :label="i.dictKey + ' ' + i.dictKeyName"
                                :value="i.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="申购数量:">
                        <RiskInputNumber
                            :input="instruction.orderAmount"
                            :inputAfter="
                                instruction.stockType == 'k'
                                    ? '张'
                                    : instruction.stockType == 'a' || instruction.stockType == 'd'
                                    ? '股'
                                    : instruction.stockType == '23' || instruction.stockType == '27' || instruction.stockType == '50'
                                    ? '份'
                                    : '股'
                            "
                            :maxlength="14"
                            :colorStyle="textColor"
                            :field="'orderAmount'"
                            :precision="0"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>

                    <el-form-item label="申购定金:">
                        <RiskInputNumber
                            :input="instruction.earnestBalance"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :maxlength="15"
                            :field="'earnestBalance'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>

                    <el-form-item label="申购金额:">
                        <RiskInputNumber
                            :input="instruction.orderBalance"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :maxlength="14"
                            :field="'orderBalance'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="申购价格:">
                        <RiskInputNumber
                            :input="instruction.orderPrice"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :maxlength="14"
                            :field="'orderPrice'"
                            :precision="2"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script lang="ts">
import Invest from '@/common/dict/invest';
import { SGU_CACHE } from '@/utils/diction-const-util';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import { convertNum, handleTextColor, highlightColor } from '@/utils/tools';

@Component({
    name: 'OfflineSubscribeForm',
    components: {
        RiskInputNumber,
        RiskEntryInput,
    },
})

// 网下申购指令表单
export default class OfflineSubscribeForm extends Vue {
    @Prop()
    detail: any;
    @Prop()
    stockInfoCache: any;
    @Prop()
    selectStockInfo: any;
    @Prop()
    isBatchFund: boolean; // 多基金指令
    @Prop()
    isBatchStock: boolean; // 多基金指令

    Invest: any = new Invest();
    handleTextColor = handleTextColor;
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    opponentCodeSelectData: any[] = []; // 交易对手下拉框数据
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据
    textColor: string = '';

    private instruction = {
        fundCode: '', // 产品代码
        fundAccountCode: '', // 组合编码
        reportCode: '', // 申报代码
        orderDirection: 'C', // 委托方向
        stockCode: '', // 证券代码
        stockNameSt: '',
        businClass: 'C',
        businessType: 'C',
        orderPrice: '',
        orderAmount: '',
        orderBalance: '', // 指令金额
        fundNameSt: '',
        fundAccountName: '',
        opponentCode: '',
        earnestBalance: '',
        marketCode: '',
        stockType: '',
    };
    stockInfo: any = {};

    async mounted() {
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        // 获取证券代码下拉框数据
        this.getstockCodeList('');
        this.getOpponentCode('');
    }

    @Watch('instruction', { immediate: true, deep: true })
    setValues() {
        this.$emit('handleSettingValue', this.instruction, '9');
    }

    @Watch('selectStockInfo', { immediate: true, deep: true })
    onWatchStockCode(newValue, oldValue) {
        if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
            this.instruction.orderPrice = '';
            this.instruction.orderBalance = '';
            this.instruction.earnestBalance = '';
            this.instruction.orderAmount = '';
            this.instruction.reportCode = this.selectStockInfo.reportCode;
            this.instruction.orderPrice = this.selectStockInfo.lowerPrice;
            this.instruction.stockCode = this.selectStockInfo.stockCode;
            this.instruction.marketCode = this.selectStockInfo.marketNo;
            this.instruction.stockType = this.selectStockInfo.stockType;
        }
    }

    @Watch('detail', { immediate: true, deep: true })
    async setForm() {
        if (this.detail && Object.keys(this.detail).length) {
            let instruction: any = {};
            for (const key in this.detail) {
                instruction[key] = this.detail[key];
            }
            await this.getstockCodeList(this.detail.stockCode);
            this.stockInfo = this.stockCodeSelectData.find(item => item.stockCode === this.detail.stockCode);
            instruction.reportCode = this.stockInfo?.reportCode;
            instruction.marketCode = this.stockInfo?.marketNo;
            this.instruction = JSON.parse(JSON.stringify(instruction));
            this.stockInfo.marketCode = this.stockInfo?.marketNo;
            this.stockInfo.stockNameSt = this.stockInfo?.stockName; // 返回的stockName实际是简称
            // this.calEarnestBalance(this.instruction.orderBalance, this.stockInfo);
            this.$emit('getStockInfo', this.stockInfo);
        }
    }

    /**
     * 判断字段颜色
     */
    @Watch('instruction', { immediate: true, deep: true })
    handleFieldColor() {
        if (this.instruction.orderDirection === 'C') {
            this.textColor = highlightColor()[1];
        } else {
            this.textColor = highlightColor()[0];
        }
    }

    get computedFundAccountCodeSelectData(): any {
        return this.fundAccountCodeSelectData[this.instruction.fundCode];
    }

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.instruction[field] = value;
        if (['orderPrice', 'orderAmount'].includes(field)) {
            if (value !== '') {
                this.handlePriceOrAmountChange();
            }
        } else if (field === 'orderBalance') {
            this.handleOrderBalanceChange(value);
        }
    }

    getEntryslist(val: any) {
        this.instruction.fundCode = val;
        this.handleFundCodeChange(val);
    }

    // 获取交易对手方数据
    getOpponentCode(value: string) {
        this.$axios
            .post('/dict/opponent/select', {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.opponentCodeSelectData = res;
            });
    }

    handleOpponentVisibleChange(val: any) {
        if (!val) {
            this.getOpponentCode('');
        }
    }

    handleFundCodeChange(val: string): void {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === val) || {};
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || [])[0] || {};
        this.instruction.fundNameSt = fund.fundNameSt;
        this.instruction.fundAccountCode = fundAccount.fundAccountCode;
        this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    handleFundAccountCodeChange(value: string) {
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || []).find(item => item.fundAccountCode === value) || {};
        this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    handleStockCode(stockCode: string): void {
        this.instruction.orderPrice = '';
        this.instruction.orderBalance = '';
        this.instruction.earnestBalance = '';
        this.instruction.orderAmount = '';
        if (stockCode) {
            this.stockInfo = this.stockCodeSelectData.find(item => item.stockCode === stockCode);
            this.stockInfo.stockNameSt = this.stockInfo.stockName;
            this.stockInfo.marketCode = this.stockInfo.marketNo;
            this.instruction.reportCode = this.stockInfo.reportCode;
            this.instruction.orderPrice = this.stockInfo.lowerPrice;
            this.instruction.marketCode = this.stockInfo.marketNo;
            this.instruction.stockType = this.stockInfo.stockType;
        } else {
            this.stockInfo = {};
        }
        this.$emit('getStockInfo', this.stockInfo, '9');
    }

    handlePriceOrAmountChange() {
        let orderBalance = (Number(this.instruction.orderPrice || '0') * Number(this.instruction.orderAmount || '0')).toString();

        if (convertNum(orderBalance) === false || Number(orderBalance) > 99999999999999.99) {
            this.yh_message_error('申购金额不能大于99999999999999.99!');
            return;
        }
        this.instruction.orderBalance = orderBalance.toString();
        if (this.selectStockInfo && JSON.stringify(this.selectStockInfo) != '{}') {
            this.calEarnestBalance(this.instruction.orderBalance, this.selectStockInfo);
        } else if (JSON.stringify(this.stockInfo) != '{}') {
            this.calEarnestBalance(this.instruction.orderBalance, this.stockInfo);
        }
    }

    handleOrderBalanceChange(val: any) {
        this.instruction.orderAmount = parseInt(
            (Number(this.instruction.orderBalance || '0') / Number(this.instruction.orderPrice || '0')).toString()
        ).toString();
        if (this.selectStockInfo && JSON.stringify(this.selectStockInfo) != '{}') {
            this.calEarnestBalance(this.instruction.orderBalance, this.selectStockInfo);
        } else if (JSON.stringify(this.stockInfo) != '{}') {
            this.calEarnestBalance(this.instruction.orderBalance, this.stockInfo);
        }
    }

    selectFocus(e) {
        let value = e.target.value;
        if (!value) {
            this.getstockCodeList('');
        }
    }

    // 防抖
    debounce(fn, delay) {
        let timer = null;
        return function() {
            if (timer !== null) {
                clearTimeout(timer);
            }
            timer = setTimeout(() => {
                // 对要调用的函数的this进行绑定，二选一
                // 第一种方式
                // fn.apply(this,arguments)
                // arguments 可以用来传递值
                // 第二种方式  还可以使用  fn.call(this)  来绑定this
                fn.call(this);
            }, delay);
        };
    }

    handleStockVisibleChange(val) {
        if (!val) {
            // this.getstockCodeList('');
            // let input = (this.$refs.searchSelect as any).$children[0].$refs.input;
            // input.blur();
        }
    }

    // 获取证券代码下拉框数据
    async getstockCodeList(val: string | undefined) {
        this.selectLoading = true;
        await this.$axios
            .post('/position/stock/offlineSubs', {
                paging: {
                    currentPage: 1,
                    pageSize: 20,
                },
                stockNameOrCode: val,
            })
            .then((res: any) => {
                this.stockCodeSelectData = res.list || [];
                this.selectLoading = false;
            });
    }

    // 申购定金 = 申购金额 * 定金比例 + 定金金额
    calEarnestBalance(orderBalance, stockInfo) {
        this.instruction.earnestBalance = (
            Number(orderBalance || '0') * Number(stockInfo.earnestRatio || '0') +
            Number(stockInfo.earnestBalance || '0')
        ).toString();
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/order-form';
</style>
